import axios from "axios"
import { getToken } from "./storage/cookies"
import { ElLoading, ElMessage } from "element-plus"
import { useUserStore } from "@/store/modules/user"
import router from "@/router"

let loadingInstance: any = null

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 360000
})

service.interceptors.request.use(
  (config) => {
    loadingInstance = ElLoading.service({ background: "transparent" })
    // config.headers.Authorization = "Bearer " + getToken()
    config.headers.Authorization = getToken()
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    loadingInstance.close()

    const res = response.data

    if (![0].includes(+res.code)) {
      ElMessage.error(res.msg || "请求报错")

      // 401: Token 过期
      if (res.code == 401) {
        useUserStore().logout()
        router.push("/login")
      }

      // 403: 没有权限
      if (res.code == 403 && response.config.url !== "getInfo") {
        router.push("/403")
      }

      return Promise.reject(res)
    } else {
      return res
    }
  },
  (error) => {
    loadingInstance.close()

    let { message } = error

    if (message === "Network Error") {
      message = "后端接口连接异常"
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时"
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常"
    }

    ElMessage.error(message)
    return Promise.reject(error)
  }
)

export default service
